package mia.beans;

import java.util.Date;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.hibernate.Session;

import mia.dao.UserEntityDAO;
import mia.entity.UserEntity;
import mia.util.DigesterUtil;
import mia.util.HibernateManager;

@ManagedBean(name="userLoginBean")
@SessionScoped
public class UserLoginBean {
	
	private UserEntity user = new UserEntity();

	private String loginStatus = null;
	private String loginIncorrect = "";
	
	private Date actualDate = new Date();
	
	public Date getActualDate() {
		return new Date();
	}
	public void setActualDate(Date actualDate) {
		this.actualDate = actualDate;
	}
	public UserEntity getUser() {
		return user;
	}
	public void setUser(UserEntity user) {
		this.user = user;
	}

	public String getLoginStatus() {
		return loginStatus;
	}
	public void setLoginStatus(String loginStatus) {
		this.loginStatus = loginStatus;
	}	
	public String getLoginIncorrect() {
		return loginIncorrect;
	}
	public void setLoginIncorrect(String loginIncorrect) {
		this.loginIncorrect = loginIncorrect;
	}
	public String tryLogin()
	{
		user.setPassword(DigesterUtil.getDigest(user.getPassword()));
		boolean correct = UserEntityDAO.checkIfLoginAndPasswordCorrect(user.getLogin(), user.getPassword());
		FacesContext context = FacesContext.getCurrentInstance();
		if(correct)
		{
			Session session = HibernateManager.getSession();
			user = UserEntityDAO.getUserByLogin(session, user.getLogin());
			session.close();
			context.addMessage("login",new FacesMessage(FacesMessage.SEVERITY_INFO, "Zalogowano!",""));
			this.setLoginStatus("Zalogowano"+user.getLogin());
			return "index2";
		}
		else
		{
			context.addMessage("login",new FacesMessage(FacesMessage.SEVERITY_ERROR, "Błąd logowania: spróbuj ponownie",""));
			return null;
		}
	}
	public String logout()
	{
		this.user = new UserEntity();
		this.setLoginStatus(null);
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage("login",new FacesMessage(FacesMessage.SEVERITY_INFO, "Wylogowano!",""));
		return "login2";
	}
}
